<template>
  <div class="login-bg">
    <div class="login-card">
      <div class="login-title">餐饮管理系统</div>
      <div class="login-subtitle">欢迎登录</div>
      <form @submit.prevent="handleLogin" autocomplete="off">
        <div class="input-group">
          <div class="input-wrapper">
            <input
              ref="usernameInput"
              v-model="formData.username"
              type="text"
              placeholder="请输入账号"
              :class="{ 'error': errors.username }"
              @blur="validateUsername"
              @input="clearError('username')"
              maxlength="20"
            />
            <div class="input-icon">👤</div>
          </div>
          <div v-if="errors.username" class="error-text">{{ errors.username }}</div>
        </div>

        <div class="input-group">
          <div class="input-wrapper">
            <input
              v-model="formData.password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入密码"
              :class="{ 'error': errors.password }"
              @blur="validatePassword"
              @input="clearError('password')"
              maxlength="50"
            />
            <div class="input-icon password-toggle" @click="togglePassword">
              {{ showPassword ? '👁️' : '🙈' }}
            </div>
          </div>
          <div v-if="errors.password" class="error-text">{{ errors.password }}</div>
        </div>

        <div class="form-options">
          <label class="remember-me">
            <input type="checkbox" v-model="rememberMe" />
            <span class="checkmark"></span>
            记住用户名
          </label>
        </div>

        <button class="login-btn" type="submit" :disabled="loading || !isFormValid">
          <span v-if="!loading">登 录</span>
          <span v-else class="loading-spinner">
            <div class="spinner"></div>
            登录中...
          </span>
        </button>
      </form>

      <div class="login-tips">
        <p>默认管理员账号：admin / admin123</p>
        <p>超级管理员账号：sysadmin / admin123</p>
      </div>

      <div class="login-footer">© 2025 餐饮管理系统</div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { login } from '../api/auth'
import { useRouter } from 'vue-router'
import { useMessage } from '../composables/useMessage'

const router = useRouter()
const { success, error } = useMessage()

// 表单数据
const formData = reactive({
  username: '',
  password: ''
})

// 表单验证错误
const errors = reactive({
  username: '',
  password: ''
})

// 其他状态
const loading = ref(false)
const showPassword = ref(false)
const rememberMe = ref(false)
const usernameInput = ref(null)

// 计算属性
const isFormValid = computed(() => {
  return formData.username.length >= 3 &&
         formData.password.length >= 6 &&
         !errors.username &&
         !errors.password
})

// 验证用户名
const validateUsername = () => {
  if (!formData.username) {
    errors.username = '请输入用户名'
  } else if (formData.username.length < 3) {
    errors.username = '用户名长度不能少于3位'
  } else if (!/^[a-zA-Z0-9_]+$/.test(formData.username)) {
    errors.username = '用户名只能包含字母、数字和下划线'
  } else {
    errors.username = ''
  }
}

// 验证密码
const validatePassword = () => {
  if (!formData.password) {
    errors.password = '请输入密码'
  } else if (formData.password.length < 6) {
    errors.password = '密码长度不能少于6位'
  } else {
    errors.password = ''
  }
}

// 清除错误
const clearError = (field) => {
  errors[field] = ''
}

// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

// 处理登录
const handleLogin = async () => {
  // 先验证表单
  validateUsername()
  validatePassword()

  if (!isFormValid.value) {
    error('请检查输入信息')
    return
  }

  loading.value = true

  try {
    const res = await login(formData.username, formData.password)

    // 存储登录信息
    localStorage.setItem('token', res.token)
    localStorage.setItem('userInfo', JSON.stringify({
      id: res.id,
      username: res.username,
      userType: res.userType,
      nickname: res.nickname,
      avatar: res.avatar,
      expiresIn: res.expiresIn
    }))

    // 记住用户名
    if (rememberMe.value) {
      localStorage.setItem('rememberedUsername', formData.username)
    } else {
      localStorage.removeItem('rememberedUsername')
    }

    success('登录成功！')

    // 延迟跳转，让用户看到成功提示
    setTimeout(() => {
      router.push('/')
    }, 1000)

  } catch (e) {
    error(e.message)
  } finally {
    loading.value = false
  }
}

// 组件挂载时的初始化
onMounted(async () => {
  // 恢复记住的用户名
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    formData.username = rememberedUsername
    rememberMe.value = true
  }

  // 自动聚焦到用户名输入框
  await nextTick()
  if (usernameInput.value) {
    usernameInput.value.focus()
  }
})
</script>

<style scoped>
html, body, #app {
  height: 100%;
  margin: 0;
  padding: 0;
}

.login-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(120deg, #6db3f2 0%, #1e69de 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
}

.login-card {
  width: 480px;
  background: rgba(255,255,255,0.95);
  border-radius: 18px;
  box-shadow: 0 12px 40px 0 rgba(31, 38, 135, 0.18);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 48px 40px 48px;
  backdrop-filter: blur(8px);
  border: none;
  position: relative;
}

.login-title {
  font-size: 2.2rem;
  font-weight: bold;
  color: #1e69de;
  margin-bottom: 14px;
  letter-spacing: 2px;
  text-align: center;
}

.login-subtitle {
  font-size: 1.2rem;
  color: #333;
  margin-bottom: 38px;
  text-align: center;
  opacity: 0.85;
}

.input-group {
  width: 100%;
  margin-bottom: 20px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper input {
  width: 100%;
  height: 50px;
  border: 1.5px solid #e0e0e0;
  border-radius: 10px;
  padding: 0 50px 0 18px;
  font-size: 17px;
  outline: none;
  background: rgba(255,255,255,1);
  transition: border 0.2s, box-shadow 0.2s;
  box-shadow: 0 1px 4px 0 rgba(64,158,255,0.03);
}

.input-wrapper input:focus {
  border-color: #409eff;
  box-shadow: 0 2px 8px 0 rgba(64,158,255,0.08);
}

.input-wrapper input.error {
  border-color: #f56565;
  box-shadow: 0 2px 8px 0 rgba(245, 101, 101, 0.08);
}

.input-icon {
  position: absolute;
  right: 15px;
  font-size: 18px;
  color: #999;
  user-select: none;
}

.password-toggle {
  cursor: pointer;
  transition: color 0.2s;
}

.password-toggle:hover {
  color: #409eff;
}

.error-text {
  color: #f56565;
  font-size: 12px;
  margin-top: 5px;
  margin-left: 5px;
}

.form-options {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.remember-me {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  user-select: none;
}

.remember-me input[type="checkbox"] {
  display: none;
}

.checkmark {
  width: 16px;
  height: 16px;
  border: 2px solid #ddd;
  border-radius: 3px;
  margin-right: 8px;
  position: relative;
  transition: all 0.2s;
}

.remember-me input[type="checkbox"]:checked + .checkmark {
  background-color: #409eff;
  border-color: #409eff;
}

.remember-me input[type="checkbox"]:checked + .checkmark::after {
  content: '✓';
  position: absolute;
  left: 2px;
  top: -2px;
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.login-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(90deg, #409eff 0%, #1e69de 100%);
  color: #fff;
  border: none;
  border-radius: 10px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  margin-top: 14px;
  box-shadow: 0 2px 8px 0 rgba(64,158,255,0.10);
  transition: all 0.2s;
  letter-spacing: 1px;
  position: relative;
  overflow: hidden;
  outline: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-btn:not(:disabled):hover {
  background: linear-gradient(90deg, #1e69de 0%, #409eff 100%);
  box-shadow: 0 4px 16px 0 rgba(64,158,255,0.18);
  transform: translateY(-1px);
}

.login-btn:active {
  transform: translateY(0);
}

.login-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.loading-spinner {
  display: flex;
  align-items: center;
  gap: 8px;
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255,255,255,0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.login-tips {
  margin-top: 20px;
  padding: 12px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 8px;
  width: 100%;
  text-align: center;
}

.login-tips p {
  margin: 0;
  font-size: 13px;
  color: #666;
}

.login-footer {
  margin-top: 30px;
  color: #888;
  font-size: 14px;
  opacity: 0.7;
  text-align: center;
  width: 100%;
}

@media (max-width: 600px) {
  .login-card {
    width: 98vw;
    padding: 32px 4vw 24px 4vw;
  }

  .login-title {
    font-size: 1.8rem;
  }

  .input-wrapper input {
    font-size: 16px;
  }
}
</style>